package com.ChenYaRou.www.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * @ClassName MyConnectionPool
 * @Description TODO
 * @Author 86183
 * @Date 2022/4/29 18:40
 * @Version 1.0
 **/
public class MyConnectionPool {
    private volatile static MyConnectionPool myConnectionPool;

    private final LinkedList<Connection> list=new LinkedList<>();

    private  int initSize=1;
    private int activeSize=0;
    private int freeSize=0;

    /**
     * 最长等待时间 30s
     */
    private final int maxWait=30000;


    private static  String driver = "com.mysql.cj.jdbc.Driver";
    private static  String url = "jdbc:mysql://localhost:3306/fooder";
    private static  String userName = "root";
    private static  String password = "ynbsjwrydkb5l";

    private MyConnectionPool(){}
    public static MyConnectionPool getInstance(){
        if(myConnectionPool==null){
            synchronized (MyConnectionPool.class){
                if(myConnectionPool==null){
                    myConnectionPool=new MyConnectionPool();
                }
            }
        }
        return myConnectionPool;
    }

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加连接
     */
    public void addConnection(){
        int maxSize = 20;
        if(freeSize+activeSize>= maxSize){
            //TODO 当前连接池全部都被占用
            return;
        }
        try {
            list.add(DriverManager.getConnection(url, userName, password));
            freeSize++;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return 得到的闲置的连接
     */
    public Connection getConnection(){
        if(list.size()<=0){
            addConnection();
        }
        //从连接池中获取一条连接,并从连接池中删除  如果连接是闲置的,激活连接,将激活数+1 自由闲置数-1
        Connection connection = list.remove();
        try {
            if(connection!=null || connection.isClosed()){
                activeSize++;
                freeSize--;
                return connection;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将conn放回连接池
     * @param connection
     */
    public void releaseConnection(Connection connection){
        try {
            if(connection!=null && !connection.isClosed()){
                list.add(DriverManager.getConnection(url, userName, password));
                freeSize++;
                activeSize--;
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
